package com.samlic.accumulation.ecosystem.reconciliation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;

/**
 * 默认的数据读取器
 * 
 * @author yuanpeng
 *
 */
public class DefaultContentReader implements ContentReader {

	@Override
	public void readData(File file, FileDataHandler dataHandler, String delimiter, Charset charset, int headSize,
			int columnSize) throws IOException {
		BufferedReader br = null;
		InputStreamReader isr = null;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, charset);
			br = new BufferedReader(isr);

			String line = br.readLine();
			if (line == null) {
				throw new IllegalStateException("File is empty.");
			}

			String[] headers = line.split(delimiter, headSize);
			if (headers.length != headSize) {
				throw new IllegalStateException("Header size error.");
			}

			int count = 0;
			int totalRow = Integer.parseInt(headers[1]);

			dataHandler.handleFirstLine(file, headers);
			while ((line = br.readLine()) != null) {
				String[] datas = line.split(delimiter, columnSize);
				if (columnSize > 0 && datas.length != columnSize) {
					throw new IllegalStateException("Data column size error.");
				}
				dataHandler.handleContent(datas);
				count++;
			}

			if (count != totalRow) {
				throw new IllegalStateException("Content size is inconsistent.");
			}

			dataHandler.handleEnd();
		} finally {
			IOUtils.closeQuietly(br);
			IOUtils.closeQuietly(isr);
			IOUtils.closeQuietly(fis);
		}
	}
}
